﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace KT.Expressions
{
    class ExpressionUtils
    {
        public static string PropertyToString(Expression expression)
        {
            var exp = expression;
            while (exp is UnaryExpression)
                exp = ((UnaryExpression)exp).Operand;

            var body = exp as MemberExpression;
            if (body == null)
                throw new ArgumentException("'x' should be a member expression");

            return body.Member.Name;
        }

        public static string PropertyToString(Expression<Func<object>> expression)
        {
            if (expression.NodeType != ExpressionType.Lambda)
                throw new ArgumentException("Value must be a lamda expression", "expression");

            var exp = expression.Body;
            return PropertyToString(exp);
        }

        public static string PropertyToString<T>(Expression<Func<T, object>> expression)
        {
            if (expression.NodeType != ExpressionType.Lambda)
                throw new ArgumentException("Value must be a lamda expression", "expression");

            var exp = expression.Body;
            return PropertyToString(exp);
        }
    }
}
